package com.zhangyu.shadow.repair.delegate.irregular;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.zhangyu.shadow.repair.R;
import com.zhangyu.shadow.repair.R2;
import com.zhangyu.shadow.repair.config.RequestUrls;
import com.zhangyu.shadow.repair.delegate.bean.VehicleBean;
import com.zhangyu.shadow.repair.delegate.luncher.BusDataConverter;
import com.zhangyu.shadow.repair.delegate.maintain.MaintainDelegate;
import com.zhangyu.shadow.repair.intercept.DataIntercept;
import com.zhangyu.shadow.repair.manager.AccountManager;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import st.lib.base.delegate.mvp.MvpDelegate;
import st.lib.base.net.callback.IError;
import st.lib.base.net.callback.ISuccess;
import st.lib.base.net.rx.RxRestClient;
import st.lib.base.ui.progress.sweetalert.DialogLoader;
import st.lib.base.ui.recycler.MultipleItemEntity;

/**
 * @author zhangyu
 * @date 2018/11/2
 */

public class IrregularTabFragment extends MvpDelegate<IrregularBusPresenter> implements
        IrregularBusContract.View {
    private static final String TYPE = "type";
    private static final int PAGE_SIZE = 20;

    public static IrregularTabFragment newInstance(int type) {
        Bundle arguments = new Bundle();
        IrregularTabFragment fragment = new IrregularTabFragment();
        arguments.putInt(TYPE, type);
        fragment.setArguments(arguments);
        return fragment;
    }

    @BindView(R2.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R2.id.refresh_layout)
    SwipeRefreshLayout mRefreshLayout;
    private int mType;
    private IrregularBusListAdapter mBusListAdapter;
    private String mMinDate = "";
    private int mId;
    private boolean isRefresh;
    private String mCode = "";
    private DialogLoader mDialogLoader;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mType = bundle.getInt(TYPE);
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.view_maintain_tab;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mBusListAdapter = new IrregularBusListAdapter(_mActivity,
                R.layout.item_complete_vehicle_info, null);
        mBusListAdapter.setEmptyView(R.layout.view_list_empty, (ViewGroup) mRecyclerView.getParent());
        mBusListAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                isRefresh = false;
                onLoadMore();
            }
        }, mRecyclerView);
        mDialogLoader = new DialogLoader(getContext());
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mBusListAdapter);
        mRecyclerView.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (!isFastClick()) {
                    VehicleBean vehicleBean = (VehicleBean) adapter.getItem(position);
                    if (vehicleBean != null && vehicleBean.getOperateType() == 0) {
                        gotoJiaoChe(vehicleBean);
                    }
                }
            }
        });
        mRefreshLayout.setEnabled(false);
    }

    //交车
    private void gotoJiaoChe(final VehicleBean vehicleBean) {
        mDialogLoader.showProgressDialog(true, "正在搜索", "请稍候...");
        RxRestClient.builder()
                .url(vehicleBean.getVmType() == 2 ?
                        RequestUrls.URL_SEARCH_BUS_FIX :
                        RequestUrls.URL_MAINTAIN_SEARCH_VEHICLE)
                .params("vehicleCode", vehicleBean.getVehicleCode())
                .params(AccountManager.getInstance().getBaseInfo())
                .interceptor(new DataIntercept())
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        if (response != null) {
                            MultipleItemEntity entity;
                            if (vehicleBean.getVmType() == 2) {
                                entity = BusDataConverter.convertToRepair(response);
                            } else {
                                entity = BusDataConverter.convertToMaintain(response);
                            }
                            if (entity != null) {
                                mDialogLoader.clearDialog();
                                IrregularBusDelegate parent = (IrregularBusDelegate) getParentFragment();
                                if (parent != null) {
                                    parent.start(MaintainDelegate.create(entity));
                                }
                            } else {
                                mDialogLoader.stopProgressWithFailed("数据解析错误", null);
                            }
                        } else {
                            mDialogLoader.stopProgressWithFailed("请求出错",
                                    "没有交车信息");
                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mDialogLoader.stopProgressWithFailed(msg, "请确认");
                    }
                })
                .build()
                .post();
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        onRefresh();
    }

    private void onRefresh() {
        mRefreshLayout.setRefreshing(true);
        mMinDate = "";
        mId = 0;
        isRefresh = true;
        onLoadMore();
    }

    private void onLoadMore() {
        mPresenter.getVehicleList(mType, mCode, AccountManager.getInstance()
                .getDepId(), mMinDate, mId);
    }

    @Override
    public void showLoading(String str) {

    }

    @Override
    public void hideLoading() {

    }

    @OnClick(R2.id.btn_reset)
    public void onViewClicked() {
        onRefresh();
    }

    @Override
    public void getVehicleListSuccess(ArrayList<VehicleBean> list) {
        mRefreshLayout.setRefreshing(false);
        final int size = list == null ? 0 : list.size();
        if (isRefresh) {
            mBusListAdapter.setNewData(list);
        } else {
            if (size > 0) {
                mBusListAdapter.addData(list);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            mBusListAdapter.loadMoreEnd(isRefresh);
        } else {
            VehicleBean bean = list.get(size - 1);
            mMinDate = bean.getOrderTime();
            mId = bean.getId();
            mBusListAdapter.loadMoreComplete();
        }
    }

    @Override
    public void getVehicleListFailed(int code, String msg) {
        mRefreshLayout.setRefreshing(false);
    }

    @Override
    public IrregularBusPresenter getPresenter() {
        return new IrregularBusPresenter(this);
    }
}
